package com.zt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.reggie.common.BaseContext;
import com.zt.reggie.common.R;
import com.zt.reggie.dto.OrdersDto;
import com.zt.reggie.entity.OrderDetail;
import com.zt.reggie.entity.Orders;
import com.zt.reggie.entity.ShoppingCart;
import com.zt.reggie.service.OrderDetailService;
import com.zt.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec com.zt.reggie.controller
 * @since 2023 - 02 - 28 - 20:10
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("下单成功!");
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(Integer page, Integer pageSize){
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        wrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        ordersService.page(pageInfo, wrapper);

        //orderDetail
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");

        List<OrdersDto> ordersDtoList = pageInfo.getRecords().stream().map(e -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(e, ordersDto);
            //查套餐明细
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            orderDetailWrapper.eq(OrderDetail::getOrderId, e.getNumber());
            List<OrderDetail> detailList = orderDetailService.list(orderDetailWrapper);
            ordersDto.setOrderDetails(detailList);

            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }
}
